package com.dev.base.able;

import com.dev.base.bean.BaseBean;
import com.dev.base.expand.HosScheduler;
import com.dev.base.able.IModelLisenner;
import com.dev.base.expand.TodoAny;
import com.dev.base.schedulers.HOSSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.functions.Supplier;
import io.reactivex.rxjava3.observers.DisposableObserver;

/**
 * 通用基类Model
 */
public abstract class BaseModel {
    private CompositeDisposable disposables;
    private IModelLisenner iModelLisenner;
    public void init(){
        this.disposables = new CompositeDisposable();
    }

    public void setiModelLisenner(IModelLisenner iModelLisenner) {
        this.iModelLisenner = iModelLisenner;
    }

    public void cleaner(){
        disposables.clear();
    }

    protected void todo(TodoAny any) {
        disposables.add(sampleObservable(any).subscribeOn(HosScheduler.switchTodoSubscribeOn(any.getTodoSubscribeOn()))
                .observeOn(HOSSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<BaseBean>() {
            @Override
            public void onNext(@NonNull BaseBean baseBean) {
                iModelLisenner.onHosNext(baseBean);
            }

            @Override
            public void onError(@NonNull Throwable e) {
                iModelLisenner.onHosError(any.getFlag(),e);
            }

            @Override
            public void onComplete() {
                iModelLisenner.onHosComplete(any.getFlag());
            }
        }));
    }
     Observable<BaseBean> sampleObservable(TodoAny any) {
        return Observable.defer(new Supplier<ObservableSource<? extends BaseBean>>() {
            @Override public ObservableSource<? extends BaseBean> get() throws Throwable {
                // Do some long running operation
                return Observable.just(any.getAnyThing().todo());
            }
        });
    }

}
